// 自定义 Promise 构造函数
function Promise(executor) {

  // 添加属性
  // 向实例身上 添加状态
  this.PromiseState = 'pending';
  // 向实例身上 添加值
  this.PromiseResult = null;


  // 存储实例 this
  // self _this that
  const _this = this

  // 存储 回调方法
  this.callbacks = []


  // resolve 函数
  function resolve(data) {
    if(_this.PromiseState !== 'pending') return
    _this.PromiseState = 'fulfilled';
    _this.PromiseResult = data;

    _this.callbacks.forEach(item => {
      item.onResolved(data) 
    })
  }

  // reject 函数
  function reject(data) {
    if(_this.PromiseState !== 'pending') return
    _this.PromiseState = 'rejected';
    _this.PromiseResult = data;

    _this.callbacks.forEach(item => {
      item.onRejected(data) 
    })
  }


  try {
    // 同步调用 【执行器函数】
    executor(resolve, reject);
  }catch(e){
    // throw 抛出错误 调用 reject
    reject(e)
  }

}






// 向原型上添加 then 方法
Promise.prototype.then = function(onResolved, onRejected) {
  // 存储实例 this
  const _this = this

  // 判断回调函数参数
  if (typeof onRejected !== 'function') {
    onRejected = reason => {
      throw reason
    }
  }

  if(typeof onResolved !== 'function') {
    onResolved = value => value
  }


  return new Promise( (resolve, reject) => {

    // 封装改变状态函数
    function callback(type) {
      try {
        let result = type(_this.PromiseResult)
        if (result instanceof Promise) {
          result.then( v => {
            resolve(v)
          }, r => {
            reject(r)
          })
        } else {
          resolve(result)
        }
      }catch(e) {
        reject(e)
      }
    }

    // 判断 当前Promise实例的 状态
    if (this.PromiseState === 'fulfilled') {
      callback(onResolved)
    }

    if (this.PromiseState === 'rejected') {
      callback(onRejected)
    }

    if (this.PromiseState === 'pending') {
      this.callbacks.push({
        onResolved: function() {
          callback(onResolved)
        },
        onRejected: function() {
          callback(onRejected)
        }
      })
    }

  })
}




// 向原型上添加 catch 方法
Promise.prototype.catch = function(onRejected) {

  return this.then(undefined, onRejected);
}




// 添加 resolve 方法
Promise.resolve = function(value) {
  // 返回Promise 对象
  return new Promise( (resolve, reject) => {
    // 判断 传入的是不是 Promise
    if (value instanceof Promise) {
      value.then(v => {
        resolve(v)
      }, r => {
        reject(r)
      })
    }else {
      // 状态设置为成功
      resolve(value)
    }
  });
}



// 添加 reject 方法
Promise.reject = function(reason) {
  return new Promise( (resolve, reject) => {
    reject(reason)
  })
}
